package com.sharding.demo.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.sharding.demo.config.CloudHintShardingAlgorithm;
import com.sharding.demo.config.HintType;
import com.sharding.demo.config.HitManagerConfig;
import com.sharding.demo.entity.Staff;
import com.sharding.demo.entity.Student;
import com.sharding.demo.service.StaffService;
import com.sharding.demo.service.StudentService;
import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
import org.apache.shardingsphere.infra.hint.HintManager;
import org.apache.shardingsphere.spring.boot.ShardingSphereAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/staff")
public class StaffController {

    @Autowired
    private StaffService staffService;

    @Resource
    private HitManagerConfig hitManagerConfig;




    @PostMapping("/save")
    public String save(@RequestBody Staff staff) {
        ShardingSphereDataSource shardingSphereDataSource;
        ShardingSphereAutoConfiguration shardingSphereAutoConfiguration;
        hitManagerConfig.initShardingSphere("111111");
        staffService.save(staff);
        hitManagerConfig.closeShardingSphere();
        return "success";
    }

    public void exe(DataSource dataSource){
        try {
            Class<?> clazz = dataSource.getClass();// 获取PrivateClass整个类

            Field[] fs = clazz.getDeclaredFields();// 获取PrivateClass所有属性
            for (int i = 0; i < fs.length; i++) {
                fs[i].setAccessible(true);// 将目标属性设置为可以访问
                System.out.println("赋值前：" + fs[i].getName() + ":" + fs[i].get(dataSource));
            }

         /*   Method[] ms = clazz.getDeclaredMethods();// 获取PrivateClass所有的方法
            for (int i = 0; i < ms.length; i++) {
                ms[i].setAccessible(true);// 将目标属性设置为可以访问
                System.out.println("方法 ： " + ms[i].getName());//输出所以方法的名称
            }
            Method m = clazz.getDeclaredMethod("url");
            m.setAccessible(true);
            System.out.println("url方法返回值：" + m.invoke(dataSource));//得到结果应该是重新赋值后的值null:null*/

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }  catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/findAll")
    public List<Staff> findAll() {
        hitManagerConfig.initShardingSphere("111111");
        List<Staff>  staffList = staffService.findAll();
        hitManagerConfig.closeShardingSphere();
        return staffList;
    }


}
